package handlers

import (
	"net/http"
	"product-management-system/config"
	"product-management-system/models"
	"product-management-system/utils"

	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
)

type RegisterRequest struct {
	Username string `json:"username" binding:"required"`
	Password string `json:"password" binding:"required"`
	Role     string `json:"role" binding:"required"`
}

type LoginRequest struct {
	Username string `json:"username" binding:"required"`
	Password string `json:"password" binding:"required"`
}

type APIKeyRequest struct {
	Description string `json:"description" binding:"required"`
}

// Register 用户注册
func Register(c *gin.Context) {
	var req RegisterRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求参数"})
		return
	}

	// 检查用户名是否已存在
	var existingUser models.User
	if result := config.DB.Where("username = ?", req.Username).First(&existingUser); result.Error == nil {
		c.JSON(http.StatusConflict, gin.H{"error": "用户名已存在"})
		return
	}

	// 加密密码
	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "密码加密失败"})
		return
	}

	// 创建新用户
	user := models.User{
		Username: req.Username,
		Password: string(hashedPassword),
		Role:     req.Role,
	}

	if result := config.DB.Create(&user); result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "用户创建失败"})
		return
	}

	c.JSON(http.StatusCreated, gin.H{"message": "用户注册成功"})
}

// Login 用户登录
func Login(c *gin.Context) {
	var req LoginRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求参数"})
		return
	}

	// 查找用户
	var user models.User
	if result := config.DB.Where("username = ?", req.Username).First(&user); result.Error != nil {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "用户名或密码错误"})
		return
	}

	// 验证密码
	if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.Password)); err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "用户名或密码错误"})
		return
	}

	// 生成JWT token
	token, err := utils.GenerateJWT(user.Username, user.Role)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "token生成失败"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"token": token})
}

// GenerateAPIKey 生成API key
func GenerateAPIKey(c *gin.Context) {
	var req APIKeyRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求参数"})
		return
	}

	// 生成新的API key
	apiKey, err := utils.GenerateAPIKey()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "API key生成失败"})
		return
	}

	// 保存API key到数据库
	key := models.APIKey{
		Key:         apiKey,
		Description: req.Description,
		Status:      "active",
	}

	if result := config.DB.Create(&key); result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "API key保存失败"})
		return
	}

	c.JSON(http.StatusCreated, gin.H{"api_key": apiKey})
}

// ListAPIKeys 获取API key列表
func ListAPIKeys(c *gin.Context) {
	var keys []models.APIKey
	if result := config.DB.Find(&keys); result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取API key列表失败"})
		return
	}

	c.JSON(http.StatusOK, keys)
}

// RevokeAPIKey 撤销API key
func RevokeAPIKey(c *gin.Context) {
	keyID := c.Param("id")

	result := config.DB.Model(&models.APIKey{}).Where("id = ?", keyID).Update("status", "revoked")
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "API key撤销失败"})
		return
	}

	if result.RowsAffected == 0 {
		c.JSON(http.StatusNotFound, gin.H{"error": "API key不存在"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "API key已撤销"})
}